package fr.gdi.android.news;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.appwidget.AppWidgetManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import fr.gdi.android.news.utils.Constants;
import fr.gdi.android.news.utils.Constants.Actions;
import fr.gdi.android.news.utils.Constants.Configuration;
import fr.gdi.android.news.utils.Constants.ExtraTags;
import fr.gdi.android.news.utils.Constants.Preferences;
import fr.gdi.android.news.utils.Constants.URI;
import fr.gdi.android.news.utils.FeedUtils;
import fr.gdi.android.news.utils.IOUtils;
import fr.gdi.android.news.utils.LogUtils;
import fr.gdi.android.news.utils.PreferenceUtils;
import fr.gdi.android.news.utils.Utils;
import fr.gdi.android.news.widgets.ScrollableNewsWidget;

public class ConfigurationActivity extends PreferenceActivity implements OnPreferenceClickListener
{
    private static final int ABOUT_DIALOG = 1;
    private static final int SAVE_PREFS = 2;
    private static final int CLEAR_THUMB_DLG = 1200;
    private static final int THUMB_SIZE_WARNING_DIALOG = 1202;
    
    private final static SimpleDateFormat SDF = new SimpleDateFormat("yyyyMMdd");
    
    private final static int requestSelectFile = 2;
    
    
    
    private final static int doAppearanceActivity = 4;
    
    private Integer appWidgetId;
    
    private boolean liveWidget;
    
    private boolean needReload = true;
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        PreferenceUtils.setUpdateInterval(this, PreferenceUtils.getUpdateInterval(this));
        
        Intent launchIntent = getIntent();
        Bundle extras = launchIntent.getExtras();
        if (extras != null)
        {
            appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
            liveWidget = extras.getBoolean(Constants.Configuration.LIVE_WIDGET, false);
            needReload = !liveWidget;
        }
        
        setupPreferences();
        
        setupAction("EDIT_FEED");
        
        if (appWidgetId != null)
        {
            setupAction("SAVE");
        }
        else 
        {
            setupAction("SHARE_TARGETS");
            setupAction("CLEAR_THUMB_CACHE");
            
        }
        setupAction("APPEARANCE");
        
        Intent intent = new Intent(this, NotificationUpdater.class); 
        intent.setAction(Actions.START_NOTIFICATION);
        this.sendBroadcast(intent);
    }
    
    private boolean doNotShowAgain;
    protected Dialog onCreateDialog(int id)
    {
        switch (id)
        {
            case THUMB_SIZE_WARNING_DIALOG:
                final Context ctx = this;
                
                AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
                AlertDialog dlg = builder1.create();
                dlg.setTitle(getString(R.string.appearance));
                LayoutInflater inflater1 = getLayoutInflater();
                View view1 = inflater1.inflate(R.layout.appearance_warning, null);
                TextView tv1 = (TextView) view1.findViewById(R.id.appearance_warning_text);
                tv1.setText(R.string.thumb_warning_text);
                CheckBox box = (CheckBox) view1.findViewById(R.id.donot_whow_again_cb);
                box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
                    {
                        doNotShowAgain = isChecked;
                    }
                });
                dlg.setView(view1);
                dlg.setButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which)
                    {
                        dialog.cancel();
                    }
                });
                dlg.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog)
                    {
                        PreferenceUtils.setBooleanPreference(ctx, "THUMB_SIZE_WARNING", doNotShowAgain);
                    }
                });
                return dlg;
            case CLEAR_THUMB_DLG:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage(this.getString(R.string.confirm_clear_thumb_cache_message))
                       .setTitle(this.getString(R.string.confirm_clear_thumb_cache_title))
                       .setCancelable(true)
                       .setPositiveButton(this.getString(R.string.ok), new DialogInterface.OnClickListener() {
                           public void onClick(DialogInterface dialog, int id) {
                               new Thread(new Runnable() {
                                   @Override
                                   public void run()
                                   {
                                       IOUtils.clearThumbnailCache();                    
                                   }
                               }).start();
                               dialog.cancel();
                           }
                       })
                       .setNegativeButton(this.getString(R.string.cancel), new DialogInterface.OnClickListener() {
                           public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                           }
                       })
                       ;
                AlertDialog alert = builder.create();
                return alert;
            case ABOUT_DIALOG:
                LayoutInflater inflater = getLayoutInflater();
                View view = inflater.inflate(R.layout.about_dialog, (ViewGroup) findViewById(R.id.about_root));
                TextView textView = ((TextView) view.findViewById(R.id.about_text_id));
                textView.setMovementMethod(LinkMovementMethod.getInstance());
                textView.setFadingEdgeLength(0);
                textView.setVerticalFadingEdgeEnabled(false);
                
                // AlertDialog alertDialog = new
                // AlertDialog.Builder(this).setView(view).create();
                // alertDialog.setTitle(getString(R.string.about));
                // alertDialog.setIcon(R.drawable.icon);
                
                final Dialog alertDialog = new Dialog(this, R.style.WideDialogTheme);
                alertDialog.getWindow().setLayout(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                alertDialog.setContentView(view);
                
                View v = ((TextView) view.findViewById(R.id.ok));
                v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v)
                    {
                        alertDialog.dismiss();
                    }
                });
                
                return alertDialog;
            case SAVE_PREFS:
                final Activity activity = this;
                LayoutInflater saveInflater = getLayoutInflater();
                final View dialogView = saveInflater.inflate(R.layout.feed_file_name_dialog, null);
                final TextView tv = (TextView) dialogView.findViewById(R.id.feed_filename);
                
                tv.setText("preferences_" + SDF.format(new Date()) + ".xml", BufferType.EDITABLE);
                
                AlertDialog dialog = new AlertDialog.Builder(this).setView(dialogView).setNegativeButton(R.string.cancel,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which)
                            {
                                dialog.dismiss();
                            }
                        }).create();
                dialog.setTitle(getString(R.string.export_feeds));
                dialog.setCancelable(true);
                dialog.setButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which)
                    {
                        try
                        {
                            String filename = tv.getText().toString();
                            PreferenceUtils.savePreferences(activity, filename);
                            Utils.showSuccess(activity, activity.getString(R.string.preferences_save_success));
                        }
                        catch (Exception e)
                        {
                            Log.e(this.getClass().getName(), "Unable to save preferences", e);
                            Utils.showError(activity, activity.getString(R.string.preferences_save_error));
                        }
                        finally
                        {
                            dialog.dismiss();
                        }
                    }
                });
                return dialog;
            default:
                return null;
        }
    }
    
    @Override
    protected void onPause()
    {
        UpdateService.register(this);
        super.onPause();
    }
    
    private void setupPreferences()
    {
        
        if (appWidgetId == null)
        {
            addPreferencesFromResource(R.xml.preferences);
            setupTapActionPreference();
            
            final Context context = this;
            findPreference(Preferences.UPDATE_INTERVAL).setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue)
                {
                    UpdateService.register(context);
                    return true;
                }
            });
            
            final CheckBoxPreference showImagePref = (CheckBoxPreference) findPreference(Preferences.MOBILIZER_SHOW_IMAGES);
            String mobilizer = PreferenceUtils.getStringPreference(this, Preferences.MOBILIZER_KEY, null, Configuration.NO_MOBILIZER);
            showImagePref.setEnabled(TextUtils.equals(mobilizer, Configuration.GOOGLE));
            showImagePref.setSummary(showImagePref.isChecked() ? R.string.mobilizer_show_images_summary : R.string.mobilizer_hide_images_summary);
            
            ListPreference pref = (ListPreference) findPreference(Preferences.MOBILIZER_KEY);
            pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue)
                {
                    showImagePref.setEnabled(TextUtils.equals((String) newValue, Configuration.GOOGLE));
                    return true;
                }
            });
            
            final CheckBoxPreference notifPref = (CheckBoxPreference) findPreference(Preferences.SHOW_ONGOING_NOTIFICATION);
            final ListPreference notifColorPref = (ListPreference) findPreference(Preferences.NOTIFICATION_COLOR);
            notifPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference arg0, Object newValue)
                {
                    Intent intent = new Intent(Actions.START_NOTIFICATION);
                    Boolean show = (Boolean) newValue;
                    context.sendBroadcast(intent);
                    
                    notifColorPref.setEnabled(show);
                    
                    return true;
                }
            });
            
            notifColorPref.setEnabled(PreferenceUtils.getBooleanPreference(context, Preferences.SHOW_ONGOING_NOTIFICATION));
            
            notifColorPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue)
                {
                    Intent intent = new Intent(Actions.START_NOTIFICATION);
                    context.sendBroadcast(intent);
                    return true;
                }
            });
            
            showImagePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue)
                {
                    preference.setSummary((Boolean) newValue ? R.string.mobilizer_show_images_summary : R.string.mobilizer_hide_images_summary);
                    return true;
                }
            });
            
            Preference thumbWidthPref = findPreference(Constants.Preferences.THUMB_SIZE);
            thumbWidthPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference arg0, Object arg1)
                {
                    if ( arg1 != null ) 
                    {
                        Integer val = (Integer) arg1;
                        if ( val > 192 ) 
                        {
                            boolean hideWarning = PreferenceUtils.getBooleanPreference(ConfigurationActivity.this, "THUMB_SIZE_WARNING");
                            if (!hideWarning)
                            {
                                showDialog(THUMB_SIZE_WARNING_DIALOG);
                            }
                        }
                    }
                    return true;
                }
            });
            
        }
        else
        {
            addPreferencesFromResource(R.xml.widget_settings);
            
            final Context context = this;
            findPreference(Preferences.UPDATE_INTERVAL).setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue)
                {
                    UpdateService.register(context);
                    return true;
                }
            });
            
            setupAction("SELECT_FEED");
            
            EditTextPreference widgetTitle = (EditTextPreference) findPreference(Preferences.DEFAULT_TITLE_KEY);
            widgetTitle.setKey(Constants.Preferences.WIDGET_TITLE_PREF + appWidgetId);
            widgetTitle.setText(PreferenceUtils.getWidgetTitle(this, appWidgetId));
            widgetTitle.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue)
                {
                    needReload = true;
                    return true;
                }
            });
            
            EditTextPreference widgetMaxNews = (EditTextPreference) findPreference(Preferences.MAX_FEEDS);
            widgetMaxNews.setKey(PreferenceUtils.getWidgetPreferenceKey(Constants.Preferences.MAX_FEEDS, appWidgetId));
            widgetMaxNews.setText(Integer.toString(PreferenceUtils.getIntFromStringPreference(this, Preferences.MAX_FEEDS, appWidgetId)));
            
            ListPreference cropNews = (ListPreference) findPreference(Preferences.CROP_DESCRIPTION_KEY);
            int cropLength = PreferenceUtils.getCropLength(this, appWidgetId);
            
            cropNews.setKey(PreferenceUtils.getWidgetPreferenceKey(Constants.Preferences.CROP_DESCRIPTION_KEY, appWidgetId));
            cropNews.setValue(Integer.toString(cropLength));
            
            if (liveWidget)
            {
                Preference savePreference = findPreference("SAVE");
                savePreference.setTitle(R.string.update_widget_configuration);
            }
            
            CheckBoxPreference hideHeader = (CheckBoxPreference) findPreference(Preferences.HIDE_HEADER);
            hideHeader.setKey(PreferenceUtils.getWidgetPreferenceKey(Constants.Preferences.HIDE_HEADER, appWidgetId));
            hideHeader.setChecked(PreferenceUtils.getBooleanPreference(context, Constants.Preferences.HIDE_HEADER, appWidgetId));
        }
        
    }
    
    private void setupTapActionPreference()
    {
        final PackageManager packageManager = this.getPackageManager();
        final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
        
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        String[] values = new String[list.size() + 2];
        String[] entries = new String[list.size() + 2];
        
        for (int u = 0; u < list.size(); u++)
        {
            ResolveInfo info = list.get(u);
            String label = info.loadLabel(packageManager).toString();
            ActivityInfo activityInfo = info.activityInfo;
            entries[u + 1] = label;
            values[u + 1] = activityInfo.packageName + "/" + activityInfo.name;
        }
        
        entries[0] = this.getString(R.string.use_builtin_browser);
        values[0] = Constants.Configuration.USE_BUILTIN_BROWSER;
        
        entries[entries.length - 1] = this.getString(R.string.do_nothing);
        values[values.length - 1] = Constants.Configuration.DO_NOTHING_ON_TAP;
        
        ListPreference listPreference = (ListPreference) findPreference("ON_TAP_ACTION");
        
        listPreference.setEntryValues(values);
        listPreference.setEntries(entries);
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu)
    {
        menu.clear();
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.xml.menu, menu);
        
        if (appWidgetId == null)
        {
            menu.getItem(0).setVisible(false);
            menu.getItem(3).setVisible(false);
            menu.getItem(4).setVisible(false);
        }
        else
        {
            menu.getItem(1).setVisible(false);
            menu.getItem(2).setVisible(false);
        }
        
        return super.onPrepareOptionsMenu(menu);
    }
    
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case R.id.about:
            {
                showDialog(ABOUT_DIALOG);
                return true;
            }
            case R.id.rate:
            {
                try
                {
                    Uri uri = Uri.parse("market://details?id=fr.gdi.android.news");
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                    return true;
                }
                catch (ActivityNotFoundException e)
                {
                    Utils.showError(this, "Unable to open Market");
                }
                return false;
            }
            case R.id.main_preference_screen:
            {
                Intent intent = new Intent(this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                this.startActivity(intent);
                return true;
            }
            case R.id.send_logs:
            {
                LogUtils.mail(this);
                return true;
            }
            case R.id.save_prefs:
            {
                showDialog(SAVE_PREFS);
                return true;
            }
            case R.id.restore_prefs:
            {
                Intent intent = new Intent(this, FileChooserActivity.class);
                startActivityForResult(intent, requestSelectFile);
                return true;
            }
            case R.id.apply_defaults:
                PreferenceUtils.applyDefaults(this, appWidgetId, !liveWidget);
                updatePreferences();
                Utils.showSuccess(this, this.getString(R.string.defaults_applied));
                return true;
            case R.id.set_defaults:
                PreferenceUtils.setDefaults(this, appWidgetId);
                Utils.showSuccess(this, this.getString(R.string.defaults_set));
                return true;
            default:
                return false;
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == requestSelectFile)
        {
            if (resultCode == RESULT_OK)
            {
                String path = data.getStringExtra(FilePickerActivity.EXTRA_FILE_PATH);
                
                try
                {
                    PreferenceUtils.restorePreferences(this, new File(path));
                    updatePreferences();
                    Utils.showSuccess(this, "Preferences successfully restored");
                }
                catch (Exception e)
                {
                    Log.e(this.getClass().getName(), "Unable to restore preferences", e);
                    Utils.showError(this, "Could not restore preferences");
                }
            }
        }
        else if (requestCode == doAppearanceActivity)
        {
            if (resultCode == RESULT_OK)
            {
                needReload |= data.getBooleanExtra("NEED_RELOAD", false);
            }
        }
        else
        {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
    
    private void updatePreferences()
    {
        for (String k : Preferences.SHARED_PREFERENCES)
        {
            String key = appWidgetId != null ? PreferenceUtils.getWidgetPreferenceKey(k, appWidgetId) : k;
            Preference p = findPreference(key);
            if (p != null)
            {
                PreferenceUtils.setPreference(this, p, k);
            }
            
        }
        
        final CheckBoxPreference showImagePref = (CheckBoxPreference) findPreference(Preferences.MOBILIZER_SHOW_IMAGES);
        if (showImagePref != null)
        {
            String mobilizer = PreferenceUtils.getStringPreference(this, Preferences.MOBILIZER_KEY, null, Configuration.NO_MOBILIZER);
            showImagePref.setEnabled(TextUtils.equals(mobilizer, Configuration.GOOGLE));
            showImagePref.setSummary(showImagePref.isChecked() ? R.string.mobilizer_show_images_summary : R.string.mobilizer_hide_images_summary);
        }
    }
    
    private void setupAction(String key)
    {
        Preference pref = findPreference(key);
        pref.setOnPreferenceClickListener(this);
    }
    
    @Override
    public boolean onPreferenceClick(Preference preference)
    {
        final String key = preference.getKey();
        
        if (key.equals("EDIT_FEED"))
        {
            Intent intent = new Intent(this, EditFeedActivity.class);
            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
            intent.putExtra(ExtraTags.TAG_SKIP_UPDATE, true);
            startActivity(intent);
        }
        else if ( key.equals("SHARE_TARGETS") )
        {
            Intent intent = new Intent(this, HideShareActivity.class);
            this.startActivity(intent);
        }
        else if ( key.equals("CLEAR_THUMB_CACHE") )
        {
            showDialog(CLEAR_THUMB_DLG);
        }
        else if (key.equals("SELECT_FEED"))
        {
            openFeedSelectionDialog();
        }
        else if ( key.equals("SHOW_ONGOING_NOTIFICATION") )
        {
            
        }
        else if (key.equals("APPEARANCE"))
        {
            Uri uri = appWidgetId != null ? URI.CONTENT_URI_WIDGET_FEEDS.buildUpon().appendEncodedPath(Integer.toString(appWidgetId)).build()
                    : URI.CONTENT_URI_FEEDS.buildUpon().build();
            
            if (appWidgetId == null)
            {
                Intent intent = new Intent(Intent.ACTION_EDIT, uri, this, AppearanceActivity.class);
                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NO_HISTORY);
                this.startActivity(intent);
            }
            else
            {
                Intent intent = new Intent(this, WidgetAppearanceActivity.class);
                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
                intent.putExtra(Configuration.LIVE_WIDGET, liveWidget);
                this.startActivityForResult(intent, doAppearanceActivity);
            }
            
            return true;
        }
        else if (key.equals("SAVE"))
        {
            if (appWidgetId != null)
            {
                String feedNames = FeedUtils.getFeedCsvList(this, appWidgetId);
                if (feedNames.length() == 0)
                {
                    Utils.showError(this, this.getString(R.string.select_feed_empty_list));
                }
                else
                {
                    Intent intent = new Intent();
                    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
                    setResult(RESULT_OK, intent);
                    
                    if (liveWidget)
                    {
                        ScrollableNewsWidget.redraw(this, appWidgetId);
                    }
                    
                    //if (needReload)
                    {
                        UpdateService.update(this, appWidgetId);
                    }
                    
                    intent = new Intent(Actions.START_NOTIFICATION);
                    this.sendBroadcast(intent);
                    
                    finish();
                }
            }
        }
        
        return false;
    }
    
    private void openFeedSelectionDialog()
    {
        List<FeedDescription> allFeedDefinitions = FeedUtils.getFeedDescriptions(this, null);
        List<FeedDescription> widgetFeeds = FeedUtils.getFeedDescriptions(this, appWidgetId);
        
        final String[] options = new String[allFeedDefinitions.size()];
        final boolean[] selections = new boolean[options.length];
        final Context context = this;
        
        for (int u = 0; u < options.length; u++)
        {
            String opt = allFeedDefinitions.get(u).name;
            options[u] = opt;
            for (FeedDescription desc : widgetFeeds)
            {
                if (TextUtils.equals(desc.name, opt))
                {
                    selections[u] = true;
                }
            }
        }
        
        AlertDialog.Builder dialog = new AlertDialog.Builder(this).setTitle("Feed selection");
        dialog = dialog.setMultiChoiceItems(options, selections, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked)
            {
                selections[which] = isChecked;
            }
        });
        dialog = dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                String feedNames = "";
                for (int i = 0; i < selections.length; i++)
                {
                    boolean b = selections[i];
                    if (b)
                    {
                        if (feedNames.length() > 0) feedNames += ",";
                        feedNames += options[i];
                    }
                }
                FeedUtils.setFeeds(context, appWidgetId, feedNames);
                needReload = true;
                dialog.dismiss();
            }
        });
        
        dialog.create().show();
    }
    
}
